# -*- coding:UTF-8 -*-
'''
Copyright 2009 http://code.google.com/p/mygaepy/. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.
  * Neither the name of http://code.google.com/p/mygaepy/ nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import os
import logging
from datetime import datetime

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.api import memcache
from google.appengine.runtime import apiproxy_errors
from urlparse import urlparse
from google.appengine.api import users

import util
from models import *
from controller import NotFound


LastModified="Tue, 30 Mar 2009 00:00:00 GMT" 

class StorePic(webapp.RequestHandler):
    def post(self):
        """
        logged,session=util.isLogin(self)
        userid=0
        if session!=None:
            userid=session.userid
        if logged==False:
            self.redirect("/login")
        """
        userid=1
        sysinfo=util.getSysInfo()
        pic=Picture()
        pic.picid=sysinfo.maxpicid
        pic.ownerid=userid
        user=util.getUserById(userid)
        pic.albumid=int(self.request.get("albumid"))
        pic.image=self.request.get("img")
        user.byteused+=len(pic.image)
        util.saveUserId(userid,user)
        pic.put()
        sysinfo.maxpicid+=1
        sysinfo.picnum+=1
        util.setSysInfo(sysinfo)
         
    def get(self):
        self.response.set_status(404)

class GetPic(webapp.RequestHandler):
    def post(self,id=1):
        self.get(id)
    def get(self,id=1):
        etag="pictspotpicid%s"%id
        user = users.get_current_user()
        is_admin = False
        if user:
            if users.is_current_user_admin():
                is_admin = True
        else:
            self.redirect("/")
            
        if util.getQuota(user) < 0:
        	"""the user has run out of quota"""
        	self.response.set_status(404)
        	return
        id=int(id)
        #cache
        match=self.request.headers.get("If-None-Match")
        if match and match==etag:
            self.response.set_status(304)
            return
        image=util.getPicture(id,1)
        if image:
            self.response.headers['Content-Type'] = "image/jpeg"
            self.response.headers['Cache-Control'] = "max-age=315360000"
            self.response.headers['Last-Modified'] = LastModified
            self.response.headers['ETag'] = etag
            self.response.out.write(image.image)
        else:
            self.response.set_status(404)

class SetCover(webapp.RequestHandler):
    def post(self,id=1):
        self.get(id)
    def get(self,id=1):
    	user = users.get_current_user()
        is_admin = False
        if user:
            if users.is_current_user_admin():
                is_admin = True
        else:
            self.redirect("/")

        referer=self.request.headers.get('referer')        
        id=int(id)
        image=util.getPicture(id,userid)
        if image and image.ownerid==userid:
            albumid=image.albumid
            query=db.GqlQuery("SELECT * FROM Album WHERE albumid=:1",albumid)
            for album in query:
                #img=images.Image(image.image)
                logging.info("changing cover of %d : %d"%(albumid,id))
                album.cover=db.Blob(images.resize(image.image,240,320))
                album.createtime=datetime.now()
                album.put()
                ###
                try:
                    r=memcache.set("album_%d"%albumid,album)
                    if not r:
                        logging.error("Memcache set album failed.")
                except apiproxy_errors.OverQuotaError, message:
                    logging.error(message)
                ###
            self.redirect(referer)
        else:
            self.response.set_status(404)


class DeletePic(webapp.RequestHandler):
    def post(self):
    	user = users.get_current_user()
        is_admin = False
        if user:
            if users.is_current_user_admin():
                is_admin = True
        else:
            self.redirect("/")

        referer=self.request.headers.get('referer',"/album/list")        
        picids=self.request.get_all("picid")
        logging.info("deleting...%s"%",".join(picids))
        if len(picids)==0:
            self.redirect(referer)
        else:
            #logging.info("SELECT * FROM Picture WHERE picid in (%s)"%",".join(picids))
            query=db.GqlQuery ("SELECT * FROM Picture WHERE picid in (%s) AND ownerid=:1"%",".join(picids),userid)
            albumid=0
            deletenum=0
            for pic in query:
                albumid=pic.albumid
                user.byteused-=len(pic.image)
                pic.delete()
                deletenum+=1
            #Album Info
            query=db.GqlQuery ("SELECT * FROM Album WHERE albumid=:1",albumid)
            for album in query:
                album.picnum-=deletenum
                album.put()
            sysinfo=util.getSysInfo()
            sysinfo.picnum-=deletenum
            util.setSysInfo(sysinfo)
            util.saveUserId(userid,user)
            self.redirect(referer)
        
    def get(self):
        self.response.set_status(404)

class ShowPic(webapp.RequestHandler):
    def post(self,picid = 1):
        self.get(picid)
    def get(self, picid = 1):
        user = users.get_current_user()
        is_admin = False
        if user:
            if users.is_current_user_admin():
                is_admin = True
        else:
            self.redirect("/")

        picid=int(picid)
        pic=util.getPicture(picid)
        
        template_values = {"picid":picid,
                           "picinfo":"",
                           }
        path = os.path.join(os.path.dirname(__file__), 'templates/picture/show.html')
        self.response.out.write(template.render(path,template_values ))
        
def main():
    application = webapp.WSGIApplication([
                                          #('/pic/store',StorePic),
                                          ('/pic/setcover/(\d+)',SetCover),
                                          ('/pic/get/(\d+)',GetPic),
                                          ('/pic/show/(\d+)', ShowPic),
                                          #('/pic/delete',DeletePic),
                                          ('/.*',NotFound)
                                          ],debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()